# Copyright (c) 2021 changwei@iscas.ac.cn
# 
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
# 
# 1. Redistributions of source code must retain the above copyright notice, this list of
#    conditions and the following disclaimer.
# 
# 2. Redistributions in binary form must reproduce the above copyright notice, this list
#    of conditions and the following disclaimer in the documentation and/or other materials
#    provided with the distribution.
# 
# 3. Neither the name of the copyright holder nor the names of its contributors may be used
#    to endorse or promote products derived from this software without specific prior written
#    permission.
# 
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
import codecs
import json
import os
import random

PERMALINK_SET = set()
PAGE_INDEX = {}


def doc_tree_to_index(json_list: list, parent_path: str='', parent_doc_id: str='/pages/') -> None:
    for index, json_dict in enumerate(json_list):
        file_name = f'{(index+1):02}.{json_dict["title"]}'
        permalink = parent_doc_id + f'{(index+1):02x}'
        if 'children' in json_dict:
            doc_tree_to_index(json_dict['children'], os.path.join(parent_path, file_name), permalink)
        else:
            PAGE_INDEX[json_dict['md_path']] = {
                # 'title': json_dict["title"],
                'target_path': os.path.join(parent_path, file_name) + '.md',
                # 'permalink': permalink,
                'front matter': {
                    'title': json_dict['title'],
                    'permalink': permalink,
                    'navbar': 'true',
                    'sidebar': 'true',
                    'prev': 'true',
                    'next': 'true',
                    'search': 'true',
                    'article': 'true',
                    'comment': 'false',
                    'editLink': 'false'
                }
            }
            assert permalink not in PERMALINK_SET, f'Duplicated permalink: {permalink}'
            PERMALINK_SET.add(permalink)


def add_all_md_to_index(input_doc_root: str, parent_path: str='') -> None:
    abs_parent_path = os.path.join(input_doc_root, parent_path)
    files = os.listdir(abs_parent_path)
    for file in files:
        relative_path = os.path.join(parent_path, file)
        if os.path.isdir(os.path.join(abs_parent_path, file)):
            add_all_md_to_index(input_doc_root, relative_path)
        elif file[-3:] == '.md':
            if relative_path in PAGE_INDEX:
                pass
            else:
                permalink = f'/pages/extra/{random.randint(0, 16777215):06x}/'
                PAGE_INDEX[relative_path] = {
                    # 'title': file.replace('.md', ''),
                    'target_path': os.path.join('_posts/zh-cn', relative_path),
                    # 'permalink': permalink,
                    'front matter': {
                        'title': file.replace('.md', ''),
                        'permalink': permalink,
                        'navbar': 'true',
                        'sidebar': 'false',
                        'prev': 'false',
                        'next': 'false',
                        'search': 'true',
                        'article': 'true',
                        'comment': 'false',
                        'editLink': 'false',
                    }
                }


def enhance_json_info_main(input_filename, output_filename, input_doc_root):
    with codecs.open(input_filename, 'r', encoding='utf-8') as inFile:
        INPUT_JSON_DICT = json.load(inFile)

    doc_tree_to_index(INPUT_JSON_DICT)
    add_all_md_to_index(input_doc_root)

    with codecs.open(output_filename, 'w', encoding='utf-8') as outFile:
        json.dump(PAGE_INDEX, outFile, indent=2, ensure_ascii=False)


if __name__ == '__main__':
    pass
